<template>
	<view class="container">
		<!--  #ifdef  MP-WEIXIN -->
		<custom background="#F5F5F5" title="会员中心"></custom>
		<!--  #endif -->

		<view class="head">
			<view class="box" data-eventsync="true" @click="getUserInfo">
				<view class="bg" data-eventsync="true">
					<image class="avatar" :src="userInfo?.avatar" lazy-load mode="widthFix" v-if="userInfo?.avatar"
						data-eventsync="true">
					</image>
					<uni-icons type="person-filled" size="40" color="#fff" v-else data-eventsync="true"></uni-icons>
				</view>

				<view class="content" data-eventsync="true">
					<view class="name" data-eventsync="true">{{ userInfo?.user_name || '游客' }}</view>
					<view class="id" data-eventsync="true">
						<text data-eventsync="true">用户ID：</text>
						<text data-eventsync="true">{{ userInfo?.id }}</text>
					</view>
					<view class="balance" data-eventsync="true">
						<text data-eventsync="true">账户余额：</text>
						<text data-eventsync="true">{{ userInfo?.money }}书币</text>
					</view>
				</view>
			</view>

			<view class="btn" @click="toUrl('/pages/user/userinfo/index')">
				<text class="txt">个人中心</text>
				<uni-icons type="right" size="14"></uni-icons>
			</view>
		</view>

		<view class="member" :class="{ isY: userInfo?.is_members == 1 }">
			<view class="content">
				<template v-if="userInfo?.is_members == 1">
					<view class="title">VIP会员卡</view>
					<view class="txt">
						<text>到期时间：</text>
						<text>{{ dayjs.unix(userInfo?.expiration_time || 0).format('YYYY-MM-DD HH:mm') }}</text>
					</view>
				</template>
				<template v-else>
					<view class="title">开通会员</view>
					<view class="txt">{{info}}</view>
				</template>
			</view>

			<view class="btn" id='open' @click="memberRef.open()" v-if="userInfo?.is_members != 1"
				v-show="shouldShowButton">立即开通</view>
		</view>

		<view class="btns">

			<view class="btn" @click="toUrl('/pages/user/orderlist/index')">
				<view class="txt">充值记录</view>

				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>

			<!--  #ifdef  MP-WEIXIN -->
			<button class="btn" open-type="contact" hover-class="none">
				<view class="txt">联系客服</view>

				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</button>
			<!--  #endif -->

			<!--  #ifdef  MP-TOUTIAO -->
			<button class="btn" open-type="im" :data-im-id="userInfo?.ttservice" hover-class="none">
				<view class="txt">联系客服</view>

				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</button>
			<!--  #endif -->

			<!-- <view class="btn">
				<view class="txt">收藏小程序</view>

				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view> -->

			<view class="btn" @click="toUrl('/pages/user/proposal/index')">
				<view class="txt">投诉建议</view>

				<uni-icons type="right" size="20" color="#999"></uni-icons>
			</view>
		</view>
		<view class="member" style="display: none; width: 500rpx; margin: 30rpx 10rpx 10rpx 120rpx;font-size: 52rpx; text-align:center;color: #ffffff;
;border-color: #D81E06;background-color: #D81E06;padding:5rpx; " @click="qiandao()">
			立刻领取书币
			<view style="font-size: 25rpx;margin-top: 5rpx;">限时活动：书币赠送大礼包（7日内）</view>
		</view>

		<view style="display: none;   text-align:center;
padding:5rpx; margin-top: 22px; color:#999;">
			<view style="padding:3rpx;letter-spacing:0.15em ;color: #D81E06;font-size: 30rpx;"> "免费书币大礼包" </view>
			<view style="padding:10rpx;letter-spacing:0.15em ;font-size: 22rpx;margin-top:10px;"> 活动说明 </view>
			<view style="padding:3rpx;letter-spacing:0.15em ;font-size: 24rpx;"> 第一天：领取<span
					style="color: #D81E06;"><span style="color: #F5F5F5;opacity:1;">0</span>50</span>书币 </view>
			<view style="padding:3rpx;letter-spacing:0.15em ;font-size: 24rpx;"> 第二天：领取<span
					style="color: #D81E06;">100</span>书币</view>
			<view style="padding:3rpx;letter-spacing:0.15em;font-size: 24rpx; "> 第三天：领取<span
					style="color: #D81E06;">200</span>书币</view>
			<view style="padding:3rpx;letter-spacing:0.15em ;font-size: 24rpx;"> 第四天：领取<span
					style="color: #D81E06;">400</span>书币</view>
			<view style="padding:3rpx;letter-spacing:0.15em ;font-size: 24rpx;"> 第五天：领取<span
					style="color: #D81E06;">500</span>书币</view>
			<view style="padding:3rpx;letter-spacing:0.15em ;font-size: 24rpx;"> 第六天：领取<span
					style="color: #D81E06;">500</span>书币</view>
			<view style="padding:3rpx;letter-spacing:0.15em ;font-size: 24rpx;"> 第七天：领取<span
					style="color: #D81E06;">500</span>书币</view>
			<view style="font-size: 10px;margin-top:20px;"> （温馨提示：防止书币丢失，点击右上角…，将小程序添加桌面。）</view>
		</view>
		<uni-popup ref="memberRef" type="bottom" :safe-area="false">
			<recharge title="付费专享内容，开通VIP可解锁并阅读全场书籍" js="0" :safe-area="false" @pay="pay" @close="close" />
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import { onShow } from '@dcloudio/uni-app'
	import { storeToRefs } from 'pinia'
	import { useUserStore } from '@/stores/user'
	import dayjs from 'dayjs'
	import { getRechargeList, payBookCurrency, androidpayBookCurrency, getsign, txtrack } from '@/api/index'
	import { toast } from '@/utils/index'
	import { GetRechargeListParam, PayBookCurrencyParam, gettxtrackParam } from '@/types/api'
	import { setUserinfo, itemOrderId } from '@/api/index'

	const myTitle = '付费专享内容，开通VIP可解锁并阅读全场书籍'
	const info = ref('立享畅享无广告阅读畅看全书')
	const userStore = useUserStore()
	const { userInfo } = storeToRefs(userStore)
	const { loginInfo } = storeToRefs(userStore)
	const memberRef = ref(null);
	const shouldShowButton = ref(true);
	const onShareAppMessage = () => {
		return {
			title: '分享的标题',
			path: 'pages/my/index', // 分享的页面路径，必须是已经存在的页面  
			imageUrl: 'https://example.com/your-image.jpg', // 可选，分享时显示的图片路径  
			success: function (res) {
				// 用户确认分享后执行的回调函数  
				console.log('分享成功', res)
			},
			fail: function (err) {
				// 用户取消分享后执行的回调函数  
				console.log('分享失败', err)
			}
		}
	}
	//支付
	const pay = async (param : PayBookCurrencyParam) => {
		try {



			//微信支付
			// #ifdef MP-WEIXIN

			const systemInfo = uni.getSystemInfoSync()

			console.log(systemInfo.osName)
			if (systemInfo.osName === 'android') {
				console.log('android')
				const res = await androidpayBookCurrency({
					number: 1,
					...param
				})
				wx.requestVirtualPayment({
					signData: res.signData,
					paySig: res.paySig,
					signature: res.signature,
					mode: 'short_series_goods',
					success: async (err) => {
						console.log('支付成功', err)
						toast('支付成功', () => {
							userStore.GetUserinfo()
							memberRef.value.close()

							const param : gettxtrackParam = {
								order_no: res.outTradeNo
							}
							const restrack = txtrack(param) || {}
							console.log(restrack)
							if (restrack) {
								//上报购买行为
								const app = getApp();
								app.sdk.track('PURCHASE', {

									value: res.track_money
								})

							}


						})
					},
					fail: (err) => {
						console.error('支付失败', err)

						// 处理支付失败后的逻辑
					},
				})

			} else {
				const res = await payBookCurrency({
					number: 1,
					...param
				})
				wx.requestPayment({
					timeStamp: res.timeStamp,
					nonceStr: res.nonceStr,
					package: res.package,
					signType: res.signType,
					paySign: res.paySign,
					success: async () => {

						toast('支付成功', () => {
							userStore.GetUserinfo()
							memberRef.value.close()

							const param : gettxtrackParam = {
								order_no: res.out_trade_no
							}
							const restrack = txtrack(param) || {}
							console.log(restrack)
							if (restrack) {
								//上报购买行为
								const app = getApp();
								app.sdk.track('PURCHASE', {

									value: res.track_money
								})

							}


						})
					},
					fail: () => {
						toast('支付失败')
					}
				})

			}
			// #endif
			//抖音支付
			// #ifdef MP-TOUTIAO
			const res = await payBookCurrency({
				number: 1,
				...param
			})
			const r = res.data || {}
			if (res.err_no == 0) {
				console.log(JSON.parse(r.data))
				const orderinfo = JSON.parse(r.data)
				// console.log(r.byteAuthorization)
				tt.requestOrder({
					data: r.data, // 请勿在前端对data做任何处理
					byteAuthorization: r.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
					success: (res) => {
						console.log('成功下单', res);

						const resorder = itemOrderId({
							itemOrderId: res.itemOrderList[0].itemOrderId,
							OrderId: res.orderId,
							order_on: orderinfo.outOrderNo
						})

						if (tt.canIUse('getOrderPayment')) {
							tt.getOrderPayment({
								orderId: res.orderId,
								success: async () => {
									toast('支付成功', () => {
										userStore.GetUserinfo()
										memberRef.value.close()
									})
								},
								fail: (respay) => {
									console.log('拉起支付参数', res.orderId);
									console.log(respay)
								},
							});
						}



					},
					fail: (res) => {
						console.log(res)
					},
				});
			} else {
				toast('支付失败')
			}
			// #endif


			// #ifdef MP-KUAISHOU
			const res = await payBookCurrency({
				number: 1,
				...param
			})
			ks.pay({
				serviceId: res.result,
				orderInfo: {
					order_no: res.order_info.order_no,
					order_info_token: res.order_info.order_info_token,
				},
				success(res) {
					// 支付成功
					toast('支付成功', () => {
						userStore.GetUserinfo()
						memberRef.value.close()
					})
				},
				fail(res) {
					// 支付失败
					toast('支付失败')
				},
			});
			// #endif
		} catch (e) {
			//TODO handle the exception
		}
	}
	//跳转
	const toUrl = (url : string) => {
		if (!url) return
		uni.navigateTo({
			url
		})
	}
	const close = () => {
		console.log('关闭')
		memberRef.value.close()
	}
	//获取用户信息
	const getUserInfo = () => {
		if (uni.getUserProfile) {
			uni.getUserProfile({
				desc: '用于获取用户个人信息',
				lang: 'zh_CN',
				success: async (res : UniApp.GetUserProfileRes) => {
					try {
						await setUserinfo({
							user_name: res.userInfo.nickName,
							avatar: res.userInfo.avatarUrl
						})
						userInfo.value.avatar = res.userInfo.avatarUrl
						userInfo.value.user_name = res.userInfo.nickName
						toast('同步成功！')
						// uni.navigateBack()

					} catch (e) {
						//TODO handle the exception
					}
				},
				fail(res) {
					console.log(res);
					toast('同步失败！')
				}
			})
		}

		// #ifdef MP-KUAISHOU
		uni.getUserInfo({
			desc: '用于获取用户个人信息',
			lang: 'zh_CN',
			success: async (res : UniApp.GetUserProfileRes) => {
				try {
					await setUserinfo({
						user_name: res.userInfo.nickName,
						avatar: res.userInfo.avatarUrl
					})
					userInfo.value.avatar = res.userInfo.avatarUrl
					userInfo.value.user_name = res.userInfo.nickName
					toast('同步成功！')
					// uni.navigateBack()
				} catch (e) {
					//TODO handle the exception
				}
			},
			fail(res) {
				console.log(res);
				toast('同步失败！')
			}
		})
		// #endif
	}
	onShow(() => {
		userStore.GetUserinfo()
		_getRechargeList()

	})
	const _getRechargeList = async () => {
		console.log('myc')
		const param : GetRechargeListParam = {
			app_id: loginInfo.value.app_id
		}
		try {
			const res = await getRechargeList(param) || {}

			const systemInfo = uni.getSystemInfoSync()
			console.log(systemInfo.osName)
			if (res.user.link_id == 0 && systemInfo.osName == 'ios') {
				toast('【由于相关规范，iOS功能暂不可用】')
				shouldShowButton.value = false
				info.value = '【由于相关规范，iOS功能暂不可用】';
			}
		} catch (e) {
			//TODO handle the exception
		}
	}
	const change = () => {
		memberRef.value.close();
	}

	const qiandao = async () => {
		try {
			const res = await getsign()
			if (res) {


				toast('恭喜您书币领取成功', () => {
					//	userStore.GetUserinfo()

				})

			}
		} catch (e) {
			//TODO handle the exception
		}
	}
</script>

<style scoped lang="scss">
	.head {
		padding: 30rpx;
		@include flex($align: center);
		flex-wrap: nowrap;

		.box {
			margin-right: 20rpx;
			flex: 1;
			@include flex($align: center);
			flex-wrap: nowrap;

			.bg {
				@include size(120rpx);
				border-radius: 50%;
				background: #D0D0D0;
				@include center(flex);

				.avatar {
					@include size(120rpx);
					border-radius: 50%;
				}
			}

			.content {
				margin-left: 30rpx;
				flex: 1;
				overflow: hidden;

				.name {
					@include tx(32rpx);
					color: #333;
				}

				.id {
					margin-top: 20rpx;
					@include tx(28rpx);
					color: #999;
				}

				.balance {
					margin-top: 16rpx;
					@include tx(28rpx);
				}
			}
		}

		.btn {
			padding: 12rpx 0;
			@include flex($align: center);
			@include tx(28rpx);
			color: #999;

			.txt {
				padding-right: 4rpx;
			}
		}
	}

	.member {
		margin: 30rpx;
		padding: 30rpx;
		background: #DADDE4;
		border-radius: 16rpx;
		transition: all .4s;
		@include flex($align: center);

		&.isY {
			background: #2F2F2F;

			.content {
				.title {
					color: #F8DDCC;
				}

				.txt {
					color: #E1DAD0;
				}
			}
		}

		.content {
			flex: 1;

			.title {
				@include tx(36rpx);
				font-weight: 600;
				color: #6A696E;
				transition: all .4s;
			}

			.txt {
				margin-top: 16rpx;
				@include tx(28rpx);
				color: #929196;
				transition: all .4s;
			}
		}

		.btn {
			margin-left: 20rpx;
			padding: 20rpx 28rpx;
			@include tx(28rpx);
			color: #333;
			background: #fff;
			border-radius: 34rpx;
		}
	}

	.btns {
		margin: 0 30rpx;
		padding: 20rpx 0;
		background: #fff;
		border-radius: 16rpx;

		.btn {
			padding: 28rpx 30rpx;
			@include tx(28rpx);
			text-align: left;
			border: none;
			background: transparent;
			@include flex(space-between, center);

			&::after {
				content: none;
			}

			.txt {
				flex: 1;
				color: #333;
			}
		}
	}
</style>